package com.cuitrip.business.order.detail;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import com.cuitrip.apiservice.OrderBusiness;
import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.app.MainApplication;
import com.cuitrip.app.base.CtException;
import com.cuitrip.app.base.CtFetchCallback;
import com.cuitrip.app.base.ProgressingFragment;
import com.cuitrip.app.rong.RongCloudEvent;
import com.cuitrip.business.conversation.CtConversationFragment;
import com.cuitrip.business.home.IndexActivity;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.login.proxy.LoginProxy;
import com.cuitrip.business.order.CancelOrderActivity;
import com.cuitrip.business.order.detail.event.OrderChangeEvent;
import com.cuitrip.business.order.model.OrderItem;
import com.cuitrip.business.setting.RelationActivity;
import com.cuitrip.business.user.PersonalFragment;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.im.model.CTInformationNotificationMessage;
import com.cuitrip.im.proxy.CtRongInfoProxy;
import com.cuitrip.service.R;
import com.cuitrip.util.track.TrackUtil;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.jumper.Jumper;
import com.lab.logtrack.AppLog;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.rx.bus.RxBus;
import com.lab.schemeurl.SchemeUrlActivity;
import com.lab.schemeurl.constant.Scheme;
import com.lab.utils.LogHelper;
import com.lab.utils.MessageUtils;
import com.lab.utils.ToastUtil;
import com.lab.widget.IndexViewPager;
import com.lab.widget.pager.TabPageIndicator;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Discussion;
import io.rong.imlib.model.MessageContent;
import io.rong.message.TextMessage;

/**
 * Created by baziii on 15/8/11.
 */
public class OrderFormActivity extends CustomUiFragmentActivity implements IProxyCallback {

    public static String CURRENT_TARGET;
    public static final String TAG = "OrderFormActivity";
    public static final String ORDER_ID = "OrderFormActivity.ORDER_ID";
    public static final String TARGET_ID = "OrderFormActivity.TARGET_ID";
    public static final String MOVE_TO_CONVERSATION = "OrderFormActivity.MOVE_TO_CONVERSATION";

    public static final int MESSAGE_TYPE_PERSON = 0;//用户发送信息
    public static final int MESSAGE_TYPE_SYSTEM = 1;//系统发送信息
    public static final int MESSAGE_TYPE_CLASS = 2;
    public static final String MESSAGE_TYPE = "OrderFormActivity.MESSAGE_TYPE";
    public static final String MESSAGE = "OrderFormActivity.MESSAGE";
    public static final String MESSAGE_OBJECT = "OrderFormActivity.MESSAGE_OBJECT";

    public static final int ORDER_TAB = 0X00;
    public static final int CONVERSATION_TAB = 0X01;
    public static final int INSIDER_TAB = 0X02;


    @Bind(R.id.ct_view_pager_indicator)
    TabPageIndicator mViewPagerIndicator;
    @Bind(R.id.ct_view_pager)
    IndexViewPager mViewPager;
    @Bind(R.id.ct_top_v)
    View mTopV;
    OrderViewsAdapter mAdapter;
    OrderItem mOrderItem = null;
    String orderId;

    private OrderFormFragment orderFormFragment;
    private PersonalFragment mPersonalFragment;
    private CtConversationFragment mConversationFragment;
    private Fragment emptyFragment = null;
    private boolean needRefreshFragmenet = false;

    private ApiProxy mApiProxy = new ApiProxy(this);
    private RongResultCallback rongResultCallback = new RongResultCallback(this);
    boolean showTabs = true;

    public static void start(Context context, String orderId) {
        Intent intent = new Intent(context, OrderFormActivity.class);
        intent.putExtra(ORDER_ID, orderId);
        context.startActivity(intent);
    }

    public static void startConversation(Context context, String orderId) {
        Intent intent = new Intent(context, OrderFormActivity.class);
        intent.putExtra(ORDER_ID, orderId);
        intent.putExtra(MOVE_TO_CONVERSATION, true);
        Jumper.launchActivity(context, intent);
    }

    public static Intent getStartOrderIntent(Context context, String orderId) {
        Intent intent = new Intent(context, OrderFormActivity.class);
        intent.putExtra(ORDER_ID, orderId);
        return intent;
    }

    public static Intent getStartConversationIntent(Context context, String orderId) {
        Intent intent = new Intent(context, OrderFormActivity.class);
        intent.putExtra(ORDER_ID, orderId);
        intent.putExtra(MOVE_TO_CONVERSATION, true);
        return intent;
    }

    /**
     * 预约消息后启动订单详情
     *
     * @param context
     * @param orderId
     * @param messageObject 消息主题
     * @param message       用户备注
     */
    public static void start(Context context, String orderId, MessageContent messageObject, String message) {
        Intent intent = new Intent(context, OrderFormActivity.class);
        intent.putExtra(ORDER_ID, orderId);
        if (messageObject != null) {
            intent.putExtra(MESSAGE_TYPE, MESSAGE_TYPE_CLASS);
            intent.putExtra(MESSAGE_OBJECT, messageObject);
        }
        if (!TextUtils.isEmpty(message)) {
            intent.putExtra(MESSAGE, message);
        }
        intent.putExtra(MOVE_TO_CONVERSATION, !TextUtils.isEmpty(message));
        Jumper.launchActivity(context, intent);
    }

    public void requestOrderDetail() {
        showLoading();
        renderUi(null);
        LogHelper.e(TAG, "requestOrderDetail  " + getIntent().getStringExtra(ORDER_ID));
        OrderBusiness.getOrderInfo(mApiProxy, orderId);
    }

    private void handOrderInfoResult(CtApiResponse response) {
        hideLoading();
        if (response.isResponseNormal()) {
            if (response.result instanceof OrderItem) {
                try {
                    OrderItem orderItem = (OrderItem) response.result;
                    renderUi(orderItem);
                    OrderChangeEvent orderChangeEvent = new OrderChangeEvent();
                    orderChangeEvent.orderId = orderItem.getOid();
                    RxBus.getDefault().send(orderChangeEvent);

                    if (moveToConversation && mViewPager != null) {
                        mViewPager.setCurrentItem(CONVERSATION_TAB);
                        moveToConversation = false;
                    }
                } catch (Exception e) {
                    LogHelper.e("omg", e.getMessage());
                }
            }
        } else {
            if (!TextUtils.isEmpty(response.msg)) {
                ToastUtil.toast(response.msg);
            }
        }
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response = (CtApiResponse) result.getData();
        if (ApiManager.GET_ORDER_INFO.equals(response.getApiName())) {
            handOrderInfoResult(response);
        }
        return false;
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mRightStyle = CustomUiConfig.AreaStyle.TEXT_STYLE;
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        return config;
    }

    private void refreshPersonalFragment() {
        String id = LoginInstance.getInstance().getUserInfo().getUid();
        if (id.equals(mOrderItem.getTravellerId())) {
            id = mOrderItem.getInsiderId();
        } else {
            id = mOrderItem.getTravellerId();
        }
        if (mPersonalFragment == null) {
            mPersonalFragment = new PersonalFragment();
            mPersonalFragment.setUid(id);
            mPersonalFragment.setShowService(false);
        } else {
            mPersonalFragment.setShowService(false);
            mPersonalFragment.setUid(id);
            mPersonalFragment.refreshUserInfo();
        }
    }


    private void refreshConversationFragment() {
        if (mOrderItem.enableRongConversation() || !mOrderItem.isOldConversations()) {
            if (!TextUtils.isEmpty(mOrderItem.getTargetId())) {
                sendMessage(mOrderItem.getTargetId());
                CtUserInfo info = LoginInstance.getInstance().getUserInfo();
                if (info != null) {
                    RongCloudEvent.onConversationStart(orderId,
                            mOrderItem.getOtherId(info.getUid()),
                            info.getUid(),
                            mOrderItem.getSid(),
                            mOrderItem.getTargetId());
                }

                LogHelper.e("replaceFragment", " do replace");
                CURRENT_TARGET = mOrderItem.getTargetId();
                LogHelper.e("omg member", " CURRENT_TARGET " + CURRENT_TARGET);
                if (mConversationFragment == null) {
                    mConversationFragment = CtConversationFragment.newInstance(orderId,
                            mOrderItem.isOldConversations(),
                            mOrderItem.getOtherId(info.getUid()));
                }

                RongIM.getInstance().getRongIMClient().getDiscussion(CURRENT_TARGET, rongResultCallback);
                mConversationFragment.setUri(getApplicationInfo(), mOrderItem);
            }

        }
    }


    public class OrderViewsAdapter extends FragmentPagerAdapter implements TabPageIndicator.CustomPageAdapter {

        private String[] pageTitles = new String[]{};

        public OrderViewsAdapter(FragmentManager fm, OrderItem orderItem) {
            super(fm);
            pageTitles = getResources().getStringArray(R.array.order_page_title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            StringBuilder stringBuilder = new StringBuilder();
            if (position == 0) {
                stringBuilder
                        .append(getString(R.string.booking_details));
            } else if (position == 1) {
                stringBuilder
                        .append(getString(R.string.chat));

            } else if (position == 2) {
                if (LoginInstance.getInstance().getUserInfo().isTravel()) {
                    stringBuilder
                            .append(getString(R.string.user_role_insider));
                } else {
                    stringBuilder
                            .append(getString(R.string.user_role_traveller));
                }
            }
            return stringBuilder.toString();
        }

        @Override
        public int getItemPosition(Object object) {
            LogHelper.e("replaceFragment", "getItemPosition  " + object + "  " + needRefreshFragmenet);
            if (needRefreshFragmenet && object instanceof ProgressingFragment) {
                needRefreshFragmenet = false;
                return POSITION_NONE;//返回这个表示该对象已改变,需要刷新
            } else {
                return POSITION_UNCHANGED;//反之不刷新
            }
        }

        @Override
        public int getCount() {
            int count = mOrderItem == null ? 0 : 3;
            return count;
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    LogHelper.e("omg", "new instance 0");
                    return orderFormFragment = OrderFormFragment.newInstance(mOrderItem);
                case 2:
                    refreshPersonalFragment();
                    return mPersonalFragment;
                default:
                    LogHelper.e("replaceFragment", "getfragment");
                    if (mOrderItem.enableRongConversation() || !mOrderItem.isOldConversations()) {
                        if (!TextUtils.isEmpty(mOrderItem.getTargetId())) {
                            refreshConversationFragment();
                            return mConversationFragment;
                        } else {
                            return emptyFragment = ProgressingFragment.newInstance();
                        }
                    } else {
                        return emptyFragment = ProgressingFragment.newInstance();
                    }
            }
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            super.destroyItem(container, position, object);
            if (position == 0) {
                orderFormFragment = null;
            }
        }

        @Override
        public String getIconText(int position) {
            return pageTitles[position];
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (mOrderItem != null) {
            CtUserInfo info = LoginInstance.getInstance().getUserInfo();
            if (info != null) {
                RongCloudEvent.onConversationStart(orderId,
                        mOrderItem.getOtherId(info.getUid()),
                        info.getUid(),
                        mOrderItem.getSid(),
                        mOrderItem.getTargetId());

            }
        }
    }

    public void replaceFragment() {
        LogHelper.e("replaceFragment", "replaceFragment");
        try {
            if (mOrderItem != null && !TextUtils.isEmpty(mOrderItem.getTargetId()) && emptyFragment != null) {
                needRefreshFragmenet = true;
                LogHelper.e("replaceFragment", " remove ");
                getSupportFragmentManager().beginTransaction().remove(
                        emptyFragment
                ).commit();
                emptyFragment = null;
            }
        } catch (Exception e) {
            LogHelper.e("replaceFragment", "replaceFragment error" + e.getMessage());

        }
        mAdapter.notifyDataSetChanged();
        mViewPagerIndicator.notifyDataSetChanged();
    }

    @Override
    protected void onPause() {
        super.onPause();
        CURRENT_TARGET = null;
    }


    public String buildOrderConversationTitle(OrderItem orderItem) {
        return orderItem.getOid();
    }

    public void buildConversation(final OrderItem orderItem) {
        List<String> userIds = new ArrayList<>();
        userIds.add(orderItem.getInsiderId());
        userIds.add(orderItem.getTravellerId());
        LogHelper.e("omg", "buildConversation start " + orderItem.getTravellerId() + "  -" + orderItem.getInsiderId());
        if (orderItem.getInsiderId() == null || TextUtils.isEmpty(orderItem.getInsiderId())
                || orderItem.getTravellerId() == null || TextUtils.isEmpty(orderItem.getTravellerId())
                || orderItem.getTravellerId().equals(orderItem.getInsiderId())) {
            MainApplication.getInstance().orderMemberIdError();
            MessageUtils.showToast(R.string.feedback_data_err);
            finish();
            return;
        }
        String title = buildOrderConversationTitle(orderItem);
        try {
            LogHelper.e(TAG, "startConversation ");
            RongCloudEvent.getInstance().startConversation(title, userIds, orderId, new CtFetchCallback<String>() {
                @Override
                public void onSuc(final String s) {
                    LogHelper.e(TAG, "startConversation suc build  target id" + s);
                    orderItem.setTargetId(s);
                    replaceFragment();
                    sendMessage(s);
                }

                @Override
                public void onFailed(CtException throwable) {
                    LogHelper.e(TAG, "startConversation failed build");
                    MessageUtils.showToast(throwable.getMessage());
                }
            });
        } catch (Exception e) {
            MessageUtils.showToast(R.string.feedback_no_internet_1);
        }
    }

    private boolean isSending = false;


    public void sendMessage(String targetId) {
        if (isSending) {
            return;
        }
        isSending = true;
        if (getIntent().hasExtra(MESSAGE_OBJECT)) {
            showLoading();
            MessageContent messageContent = getIntent().getParcelableExtra(MESSAGE_OBJECT);
            CtRongInfoProxy.getInstance().sendSystemMessage(targetId, (CTInformationNotificationMessage) messageContent, new RongIMClient.SendMessageCallback() {

                @Override
                public void onSuccess(Integer integer) {
                    getIntent().removeExtra(MESSAGE_TYPE);
                    getIntent().removeExtra(MESSAGE_OBJECT);
                    isSending = false;
                    hideLoading();
                }

                @Override
                public void onError(Integer integer, RongIMClient.ErrorCode errorCode) {
                    isSending = false;
                    hideLoading();
                }
            });
        }

        if (getIntent().hasExtra(MESSAGE)) {
            String message = getIntent().getStringExtra(MESSAGE);
            RongCloudEvent.getInstance()
                    .sendMessage(Conversation.ConversationType.DISCUSSION, targetId, TextMessage.obtain(message), message, message, new RongIMClient.SendMessageCallback() {
                        @Override
                        public void onError(Integer integer, RongIMClient.ErrorCode errorCode) {
                            isSending = false;
                        }

                        @Override
                        public void onSuccess(Integer integer) {
                            getIntent().removeExtra(MESSAGE);
                            isSending = false;
                        }
                    });

        }
    }

    public void renderUi(OrderItem orderItem) {
        this.mOrderItem = orderItem;
        if (orderItem != null) {
            LogHelper.e(TAG, "order target id" + orderItem);
            if (TextUtils.isEmpty(orderItem.getTargetId())) {
                buildConversation(this.mOrderItem);
            }
        }
        if (orderItem != null) {
            if (orderFormFragment != null) {
                orderFormFragment.refresh(orderItem);
            }
            if (mPersonalFragment != null) {
                refreshPersonalFragment();
            }
            if (mConversationFragment != null) {
                refreshConversationFragment();
            }
        }
        mTopV.setVisibility(showTabs ? View.VISIBLE : View.GONE);
        replaceFragment();

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        LogHelper.e("omg", "onNewIntent");
        requestData(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.ct_order_form);
        IntentFilter filter = new IntentFilter(OrderItem.ORDER_STATUS_CHANGED_ACTION);
        registerReceiver(mOrderStatusChangedReceiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mOrderStatusChangedReceiver);
        emptyFragment = null;
        orderFormFragment = null;
        mPersonalFragment = null;
        mConversationFragment = null;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        mAdapter = new OrderViewsAdapter(getSupportFragmentManager(), mOrderItem);
        mViewPager.setAdapter(mAdapter);
    }

    @Override
    public void initData() {
        if (!LoginInstance.getInstance().isLogin()) {
            LoginProxy.getInstance().gotoUserEnter(this);
            finish();
            return;
        }
        mTopbarMiddleArea.setText(R.string.booking_summary);
        mViewPager.requestDisallowInterceptTouchEvent(true);
        mViewPager.setOffscreenPageLimit(3);
        mViewPagerIndicator.setViewPager(mViewPager);
        mViewPager.setScanScroll(true);
        mViewPagerIndicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < mAdapter.getCount(); i++) {

                    if (i != position) {
                        if (position == ORDER_TAB) {
                            if (mOrderItem != null) {
                                if (LoginInstance.getInstance().getUserInfo().isTravel()) {
                                    TrackUtil.trackScreenName("/booking/summary/detail/" + mOrderItem.getStatus());
                                } else {
                                    TrackUtil.trackScreenName("/insider/booking/summary/detail/" + mOrderItem.getStatus());
                                }
                            }
                        } else if (position == CONVERSATION_TAB) {
                            if (mOrderItem != null) {
                                if (LoginInstance.getInstance().getUserInfo().isTravel()) {
                                    TrackUtil.trackScreenName("/booking/summary/chat/" + mOrderItem.getStatus());
                                } else {
                                    TrackUtil.trackScreenName("/insider/booking/summary/chat/" + mOrderItem.getStatus());
                                }
                            }
                        } else if (position == INSIDER_TAB) {
                            if (mOrderItem != null) {
                                if (LoginInstance.getInstance().getUserInfo().isTravel()) {
                                    TrackUtil.trackScreenName("/booking/summary/insider/" + mOrderItem.getStatus());
                                } else {
                                    TrackUtil.trackScreenName("/insider/booking/summary/insider/" + mOrderItem.getStatus());
                                }
                            }
                        }

                        Fragment fragment = mAdapter.getItem(i);
                        if (fragment instanceof OrderSubFragment) {
                            ((OrderSubFragment) fragment).onLeaveMe(OrderFormActivity.this);
                        }
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        requestData(getIntent());
        RongCloudEvent.ConnectRong(false);
    }

    public void requestData(final Intent intent) {
        if (intent.hasExtra(IndexActivity.CHANGE_ROLE_KEY) && intent.getBooleanExtra(IndexActivity.CHANGE_ROLE_KEY, false)) {
            final CtUserInfo info = LoginInstance.getInstance().getUserInfo();
            final int type = info.isTravel() ? CtUserInfo.USER_FINDER : CtUserInfo.USER_TRAVEL;
            showLoading();
            IProxyCallback proxyCallback = new IProxyCallback() {
                @Override
                public boolean onProxyResult(ProxyResult<?> result) {
                    hideLoading();
                    CtApiResponse response = (CtApiResponse) result.getData();
                    if (response.isResponseNormal()) {
                        info.setType(type);
                        LoginInstance.updateProfile(AppCoreRuntime.context, info, true);
                        Intent startIntent = new Intent(OrderFormActivity.this, IndexActivity.class);
                        startIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);

                        Bundle bundle = new Bundle();
                        bundle.putInt(IndexActivity.GO_TO_TAB, 1);
                        if (intent.hasExtra(ORDER_ID)) {
                            bundle.putString(SchemeUrlActivity.SchemeUrl, Scheme.CUITRIP.getSchemeName());
                            startIntent.setData(Uri.parse("cuitrip://chat?oid=" + intent.getStringExtra(ORDER_ID)));
                        }
                        startIntent.putExtras(bundle);
                        startActivity(startIntent);
                    } else {
                        if (!TextUtils.isEmpty(response.msg)) {
                            MessageUtils.showToast(response.msg);
                        }
                    }
                    return true;
                }
            };
            ApiProxy apiProxy = new ApiProxy(proxyCallback);
            UserBusiness.changeType(apiProxy, type);
        } else {
            requestDetail(intent);
        }

    }

    @Override
    public void onTopbarRightPress() {
        if (getString(R.string.setting_contact).equals(mTopbarRightArea.getText().toString())) {
            startActivity(new Intent(this, RelationActivity.class));
        } else {
            CancelOrderActivity.start(this, mOrderItem);
        }
    }

    private void requestDetail(Intent intent) {
        if (intent.getBooleanExtra(MOVE_TO_CONVERSATION, false)) {
            notifyedMoveConversation();
        }
        orderId = intent.getStringExtra(ORDER_ID);
        LogHelper.e(TAG, " request " + orderId);
        mViewPager.setCurrentItem(0);
        requestOrderDetail();
    }

    boolean moveToConversation = false;

    public void notifyedMoveConversation() {
        moveToConversation = true;
    }

    private BroadcastReceiver mOrderStatusChangedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (OrderItem.ORDER_STATUS_CHANGED_ACTION.equals(intent.getAction())) {
                if (intent.hasExtra(OrderItem.KEY_ORDER_ID) && !intent.getStringExtra(OrderItem.KEY_ORDER_ID).equals(orderId)) {
                    return;
                }
                requestOrderDetail();
            }

        }
    };

    @Override
    public void onTopbarLeftPress() {
        finish();
    }

    private static class RongResultCallback extends RongIMClient.ResultCallback<Discussion> {

        private final WeakReference<OrderFormActivity> ref;

        public RongResultCallback(OrderFormActivity ref) {
            this.ref = new WeakReference<OrderFormActivity>(ref);
        }


        @Override
        public void onSuccess(Discussion discussion) {
            if (ref.get() != null) {
                OrderFormActivity activity = ref.get();
                AppLog.d("omg member", TextUtils.join("|", discussion.getMemberIdList()));
                try {
                    if (discussion.getMemberIdList() == null || discussion.getMemberIdList().size() != 2
                            || !discussion.getMemberIdList().contains(LoginInstance.getInstance().getUserInfo().getUid())
                            ) {
                        activity.emptyFragment = activity.mConversationFragment;
                        MainApplication.getInstance().orderRongMembersizeError();
                        activity.buildConversation(activity.mOrderItem);
                    }

                } catch (Exception e) {
                    AppLog.d(TAG, "failed");
                }
                AppLog.d(TAG, "SUC " + discussion.getMemberIdList() + " : " + TextUtils.join("|", discussion.getMemberIdList()));
            }
        }

        @Override
        public void onError(RongIMClient.ErrorCode errorCode) {
            if (ref.get() != null) {
                OrderFormActivity activity = ref.get();
                LogHelper.e(TAG, " member failed " + errorCode.name() + "|" + errorCode.getMessage());
                if (errorCode.equals(RongIMClient.ErrorCode.NOT_IN_DISCUSSION)) {
                    activity.emptyFragment = activity.mConversationFragment;
                    MainApplication.getInstance().orderRongMembersizeError();
                    activity.buildConversation(activity.mOrderItem);
                }
                if (RongIMClient.ErrorCode.IPC_DISCONNECT.equals(errorCode)
                        || RongIMClient.ErrorCode.RC_NET_UNAVAILABLE.equals(errorCode)
                        || RongIMClient.ErrorCode.RC_SOCKET_DISCONNECTED.equals(errorCode)) {
                    RongCloudEvent.getInstance().forceConnect();
                }


            }
        }
    }
}
